<?php
/**     
  *
  * Copyright (c) 2009, Persistent Systems Limited
  *
  * Redistribution and use, with or without modification, are permitted 
  *  provided that the following  conditions are met:
  *   - Redistributions of source code must retain the above copyright notice, 
  *     this list of conditions and the following disclaimer.
  *   - Neither the name of Persistent Systems Limited nor the names of its contributors 
  *     may be used to endorse or promote products derived from this software 
  *     without specific prior written permission.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
/**
 * classes/connectionClass.php
 */
include("config.php");
/**
 * classes/connectionClass.php
 */
include("classes/connectionClass.php");
/**
 * classes/commonfunctions.php
 */
include("includes/commonfunctions.php");
/**
  *   This Class for Curl Request
  */
require_once 'util/curlRequest.php';

/**
  *   This Class for Authentication Request
  */
require_once 'ACS/Authentication.php';

/**
 * classes/AtomParser.php
 */
include('AtomParser.php');
/**
  * This class is part of PHP Unit test framework
  */
require_once 'PHPUnit/TestCase.php';
/**
  * This class is part of PHP Unit test framework
  */
require_once 'PHPUnit/TestResult.php';
/**
  * This class is part of PHP Unit test framework
  */
require_once 'PHPUnit/TestSuite.php';
/**
  * This class is part of PHP Unit test framework
  */
require_once 'PHPUnit.php';	
/**
  *  This Class set the environment amongs bvt,production, int, ppe
  */
require_once 'DotNetServicesEnvironment.php';
/**
  * This class generates the token 
  */
require_once 'ACS/SimpleApiAuthService.php';

 /**
   * SalesDashboardTestCases class file contanis  unit test cases for  SalesDashboard   
   */	
class SalesDashboardTestCases extends PHPUnit_TestCase 
{
  	
	/**
      * Function to validate region list 
      * Test case pass if region service validates the list of the regions 	 
      */	
    function testGetRegions()
	{
		try{
			$acmHostName = DotNetServicesEnvironment::getACMHostName();
			$serviceName = ACS_TRUSTED_SERVICE;
			$scope = new Scope(SIMPLE_API_AUTH);

			$scope->setIssuerName(ACS_TRUSTED_SCOPENAME);
			$scope->setIssuerSecret(ACS_TRUSTED_ISSUER_KEY);
			$scope->setAppliesTo(ACS_TRUSTED_AUDIENCE);

			$simpleApiAuthService = new SimpleApiAuthService($acmHostName, $serviceName);
			$simpleApiAuthService->setScope($scope);

			// Need this only from corpnet
			$httpWebProxy = new HttpWebProxy(HTTP_PROXY, HTTP_PORT);  				
			$simpleApiAuthService->setHttpWebProxy($httpWebProxy);


			$token = $simpleApiAuthService->getACSToken();
			$token =  "WRAP" . " " . 'access_token="' . urldecode($token) . '"';  

			//URL for region service
			$url = Service_Host_Name.'Region.php';

			$curlHandle = curl_init();
			curl_setopt($curlHandle, CURLOPT_URL, $url);
			curl_setopt($curlHandle, CURL_HTTP_VERSION_1_1, true);				
			//$headerValue = "WRAPv0.8" . " " . urldecode($token); 
			$headerValue = $token; 
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, Array("X-Authorization: " . $headerValue));   

			curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER,  true);
			curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION,  true);
			curl_setopt($curlHandle, CURLOPT_HTTPGET, true);
			$httpResponse = curl_exec($curlHandle);
			$curlInfo = curl_getinfo($curlHandle);
			$httpCode = $curlInfo['http_code'];
			$httpResponse = trim($httpResponse);
      
			$obj = new AtomParser($httpResponse);
			$response = $obj->parseString();
			
			foreach($response as $key=>$value){
				$resRegions[$response[$key]['RegionID']] = $response[$key]['Name'];
			}	
			
			$dB = new Database_Conn();

			$dB->prepareSql("select * from region");
			$regionsArr = $dB->getResults(); 				
			foreach($regionsArr as $key=>$value){
				$regions[$regionsArr[$key]['RegionID']] = $regionsArr[$key]['Name'];
			}	
			
			for($i=1; $i<=count($regions);$i++){				
				$this->assertEquals($resRegions[$i]['RegionID'],$regions[$i]["RegionID"]);    
				$this->assertEquals($resRegions[$i]['Name'],$regions[$i]["Name"] );				
			}
			 			 						
		} 
		catch(Exception $e)
		{	
			 $e->getMessage();
			 throw($e);
		}
	}
	
	/**
      * Function to validate product list 
      * Test case pass if product service validates the list of the products 	 
      */
	function testGetProducts()
	{
		try{
			$acmHostName = DotNetServicesEnvironment::getACMHostName();
			$serviceName = ACS_TRUSTED_SERVICE;
			$scope = new Scope(SIMPLE_API_AUTH);

			$scope->setIssuerName(ACS_TRUSTED_SCOPENAME);
			$scope->setIssuerSecret(ACS_TRUSTED_ISSUER_KEY);
			$scope->setAppliesTo(ACS_TRUSTED_AUDIENCE);

			$simpleApiAuthService = new SimpleApiAuthService($acmHostName, $serviceName);
			$simpleApiAuthService->setScope($scope);

			// Need this only from corpnet
			$httpWebProxy = new HttpWebProxy(HTTP_PROXY, HTTP_PORT);  				
			$simpleApiAuthService->setHttpWebProxy($httpWebProxy);


			$token = $simpleApiAuthService->getACSToken(); 	 
			$token =  "WRAP" . " " . 'access_token="' . urldecode($token) . '"';  

			//URL for product service
			$url = Service_Host_Name.'Product.php';

			$curlHandle = curl_init();
			curl_setopt($curlHandle, CURLOPT_URL, $url);
			curl_setopt($curlHandle, CURL_HTTP_VERSION_1_1, true);
			//$headerValue = "WRAPv0.8" . " " . urldecode($token); 
			$headerValue = $token; 
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, Array("X-Authorization: " . $headerValue));  
			
			curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER,  true);
			curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION,  true);
			curl_setopt($curlHandle, CURLOPT_HTTPGET, true);
			$httpResponse = curl_exec($curlHandle);		
			 			
			$httpResponse = trim($httpResponse);
			$obj = new AtomParser($httpResponse);
			$response = $obj->parseString();
			
			foreach($response as $key=>$value){
				$resproducts[$response[$key]['ProductID']] = $response[$key]['ProductID'];
				$resproducts[$response[$key]['Name']] = $response[$key]['Name'];
				$resproducts[$response[$key]['Cost']] = $response[$key]['Cost'];
			}		
			
			
			$dB = new Database_Conn();

			$dB->prepareSql("select * from product");
			$productArr = $dB->getResults();   				
			
			foreach($productArr as $key=>$value){
				$products[$productArr[$key]['ProductID']] = $productArr[$key]['ProductID'];
				$products[$productArr[$key]['Name']] = $productArr[$key]['Name'];
				$products[$productArr[$key]['Cost']] = $productArr[$key]['Cost'];
			}					
			
			// Verification  part 
			for($i=1; $i<=count($productArr);$i++){	
				$this->assertEquals($resproducts[$i]['ProductID'],$products[$i]["ProductID"] );
				$this->assertEquals($resproducts[$i]['Name'],$products[$i]["Name"] );                
				$this->assertEquals($resproducts[$i]['Cost'],$products[$i]["Cost"]); 									
			}		
		}  						
		
		catch(Exception $e)
		{	
			 $e->getMessage();
			 throw($e);
		}
	}

	/**
      * Function to validate list of the sales order
      * Test case pass if sales order service validates the list of the sales order	 
      */
    function testSalesOrder()
	{
		try 
		{	
			$acmHostName = DotNetServicesEnvironment::getACMHostName();
			$serviceName = ACS_TRUSTED_SERVICE;
			$scope = new Scope(SIMPLE_API_AUTH);

			$scope->setIssuerName(ACS_TRUSTED_SCOPENAME);
			$scope->setIssuerSecret(ACS_TRUSTED_ISSUER_KEY);
			$scope->setAppliesTo(ACS_TRUSTED_AUDIENCE);

			$simpleApiAuthService = new SimpleApiAuthService($acmHostName, $serviceName);
			$simpleApiAuthService->setScope($scope);

			// Need this only from corpnet
			$httpWebProxy = new HttpWebProxy(HTTP_PROXY, HTTP_PORT);  				
			$simpleApiAuthService->setHttpWebProxy($httpWebProxy);


			$token = $simpleApiAuthService->getACSToken(); 	
			$token =  "WRAP" . " " . 'access_token="' . urldecode($token) . '"';  
			
			//URL for Sales order service
			$url = Service_Host_Name.'SalesOrder.php?salespersonid=1';

			$curlHandle = curl_init();
			curl_setopt($curlHandle, CURLOPT_URL, $url);
			curl_setopt($curlHandle, CURL_HTTP_VERSION_1_1, true);
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($token); 
			$headerValue = $token; 
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, Array("X-Authorization: " . $headerValue));  

			curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER,  true);
			curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION,  true);
			curl_setopt($curlHandle, CURLOPT_HTTPGET, true);
			$httpResponse = curl_exec($curlHandle);	
			$httpResponse = trim($httpResponse);		 			
			
			
			$obj = new AtomParser($httpResponse);
			$response = $obj->parseString();
			
			foreach($response as $key=>$value){
				$resSalesOrder[$response[$key]['salesorderid']] = $response[$key]['salesorderid'];
				$resSalesOrder[$response[$key]['productid']] = $response[$key]['productid'];
				$resSalesOrder[$response[$key]['productname']] = $response[$key]['productname'];
				$resSalesOrder[$response[$key]['cost']] = $response[$key]['cost'];
				$resSalesOrder[$response[$key]['orderqty']] = $response[$key]['orderqty'];
			}	
						
			$dB = new Database_Conn();

			$dB->prepareSql("select s.salesorderid,s.productid,p.name as productname,p.cost, s.orderqty from salesorder s,product p, salesperson sp where s.productid = p.productid and s.salespersonid = sp.salespersonid and sp.salespersonid=1");
			$salesOrderArray = $dB->getResults();
			
			foreach($salesOrderArray as $key=>$value){
				$salesOrders[$salesOrderArray[$key]['salesorderid']] = $salesOrderArray[$key]['salesorderid'];
				$salesOrders[$salesOrderArray[$key]['productid']] = $salesOrderArray[$key]['productid'];
				$salesOrders[$salesOrderArray[$key]['productname']] = $salesOrderArray[$key]['productname'];
				$salesOrders[$salesOrderArray[$key]['cost']] = $salesOrderArray[$key]['cost'];
				$salesOrders[$salesOrderArray[$key]['orderqty']] = $salesOrderArray[$key]['orderqty'];				
			}	
			
			// Verification  part 
			for($i=1; $i<=count($salesOrderArray);$i++){	
				$this->assertEquals($resSalesOrder[$i]['salesorderid'],$salesOrders[$i]["salesorderid"]);
				$this->assertEquals($resSalesOrder[$i]['productid'],$salesOrders[$i]["productid"] );
				$this->assertEquals($resSalesOrder[$i]['productname'],$salesOrders[$i]["productname"] );
				$this->assertEquals($resSalesOrder[$i]['cost'],$salesOrders[$i]["cost"] );
				$this->assertEquals($resSalesOrder[$i]['orderqty'],$salesOrders[$i]["orderqty"] );								
			 }    
								
		}
		catch(Exception $exception)
        {	
			 $e->getMessage();
			 throw($e);
        }
	}
	
	/**
      * Function to validate list of the create order
      * Test case pass if create order service validates the list of the create order 	 
      */
	function testCreateOrder()
	{
		try 
		{	
			$acmHostName = DotNetServicesEnvironment::getACMHostName();
			$serviceName = ACS_TRUSTED_SERVICE;
			$scope = new Scope(SIMPLE_API_AUTH);

			$scope->setIssuerName(ACS_TRUSTED_SCOPENAME);
			$scope->setIssuerSecret(ACS_TRUSTED_ISSUER_KEY);
			$scope->setAppliesTo(ACS_TRUSTED_AUDIENCE);

			$simpleApiAuthService = new SimpleApiAuthService($acmHostName, $serviceName);
			$simpleApiAuthService->setScope($scope);

			// Need this only from corpnet
			$httpWebProxy = new HttpWebProxy(HTTP_PROXY, HTTP_PORT);  				
			$simpleApiAuthService->setHttpWebProxy($httpWebProxy);


			$token = $simpleApiAuthService->getACSToken(); 	
			$token =  "WRAP" . " " . 'access_token="' . urldecode($token) . '"';  
			

			//URL for Create Order Service 
			$url = Service_Host_Name.'CreateOrder.php';
			$data['productid'] = '1';
			$data['salespersonid'] = '2';
			$data['orderqty'] = '10';
			$curlHandle = curl_init();
			curl_setopt($curlHandle, CURLOPT_URL, $url);
			curl_setopt($curlHandle, CURL_HTTP_VERSION_1_1, true);
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($token); 
			$headerValue = $token; 
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, Array("X-Authorization: " . $headerValue));  

			curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER,  true);
			curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION,  true);			
			curl_setopt($curlHandle, CURLOPT_POST, true);
			curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $data);			
			
			$httpResponse = curl_exec($curlHandle);	   
			$httpResponse = trim($httpResponse);
			
			$dB = new Database_Conn();

			$dB->prepareSql("select ProductID,SalesPersonID,OrderQty from salesorder where SalesPersonID='2'");
			$salesOrder = $dB->getResults();   				
			
			// Verification  part 
			$this->assertEquals($data['productid'],$salesOrder[0]["ProductID"]);
			$this->assertEquals($data['salespersonid'],$salesOrder[0]["SalesPersonID"]);
			$this->assertEquals($data['orderqty'],$salesOrder[0]["OrderQty"]);			
				
		}
		catch(Exception $exception)
        {	
			 $e->getMessage();
			 throw($e);
        }
	}

	/**
      * Function to validate list of the update order
      * Test case pass if update order service validates the list of the update order 	 
      */
    function testUpdateOrder()
	{
	 try 
		{
			$acmHostName = DotNetServicesEnvironment::getACMHostName();
			$serviceName = ACS_TRUSTED_SERVICE;
			$scope = new Scope(SIMPLE_API_AUTH);

			$scope->setIssuerName(ACS_TRUSTED_SCOPENAME);
			$scope->setIssuerSecret(ACS_TRUSTED_ISSUER_KEY);
			$scope->setAppliesTo(ACS_TRUSTED_AUDIENCE);

			$simpleApiAuthService = new SimpleApiAuthService($acmHostName, $serviceName);
			$simpleApiAuthService->setScope($scope);

			// Need this only from corpnet
			$httpWebProxy = new HttpWebProxy(HTTP_PROXY, HTTP_PORT);  				
			$simpleApiAuthService->setHttpWebProxy($httpWebProxy);


			$token = $simpleApiAuthService->getACSToken(); 	 
			$token =  "WRAP" . " " . 'access_token="' . urldecode($token) . '"';  

			////URL for Update Order Service 
			$url = Service_Host_Name.'UpdateOrder.php';				
			
			$data['salesorderid']  = 1;  
			$data['productid']     = 1; 
			$data['orderqty']      = 50; 
			$data['salespersonid'] = 1; 
			$data1 = http_build_query($data,'','&');	 
			$tenMB = 10 * 1024 * 1024;  
			
			$fh = fopen("php://temp/maxmemory:{$tenMB}",'rw');   
			fwrite($fh, $data1);  
			rewind($fh);
			$handle = curl_init(); 
			curl_setopt($handle, CURLOPT_RETURNTRANSFER, true) ; 
			curl_setopt($handle, CURLOPT_URL, $url);    
			//$headerValue = "WRAPv0.8" . " " . urldecode($token);  
			$headerValue = $token; 
			curl_setopt($handle, CURLOPT_HTTPHEADER, Array("X-Authorization: " . $headerValue)); 
			curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true); 
			curl_setopt($handle, CURLOPT_PUT,true);	  
			curl_setopt($handle, CURLOPT_INFILE, $fh);     
			curl_setopt($handle, CURLOPT_INFILESIZE, strlen($data1));
			curl_setopt($handle, CURLOPT_PUT, true);   
			curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);	
			$result = curl_exec($handle);  
			  
			fclose($fh);				
			
            $dB = new Database_Conn();	 
			$dB->prepareSql("select ProductID,salesorderid,OrderQty from salesorder where SalesPersonID='1'");
			$salesOrder = $dB->getResults();
			
			// Verification  part        	
      $this->assertEquals($data['productid'],$salesOrder[0]["ProductID"]);
			$this->assertEquals($data['salesorderid'],$salesOrder[0]["salesorderid"]);
			$this->assertEquals($data['orderqty'],$salesOrder[0]["OrderQty"]);		 
				
		}
		catch(Exception $exception)
        {	
			$e->getMessage();			
			throw($e);
        }
	}

	/**
      * Function to validate list of the Sales data on the yearly bases 
      * Test case pass if sales data service validates the list of the sales data	 
      */
    function testSalesData()
	{
		try 
		{	
			$acmHostName = DotNetServicesEnvironment::getACMHostName();
			$serviceName = ACS_TRUSTED_SERVICE;
			$scope = new Scope(SIMPLE_API_AUTH);

			$scope->setIssuerName(ACS_TRUSTED_SCOPENAME);
			$scope->setIssuerSecret(ACS_TRUSTED_ISSUER_KEY);
			$scope->setAppliesTo(ACS_TRUSTED_AUDIENCE);

			$simpleApiAuthService = new SimpleApiAuthService($acmHostName, $serviceName);
			$simpleApiAuthService->setScope($scope);

			// Need this only from corpnet
			$httpWebProxy = new HttpWebProxy(HTTP_PROXY, HTTP_PORT);  				
			$simpleApiAuthService->setHttpWebProxy($httpWebProxy);


			$token = $simpleApiAuthService->getACSToken(); 	
			$token =  "WRAP" . " " . 'access_token="' . urldecode($token) . '"';  
			
			//	URL for Sales Data
			$url = Service_Host_Name.'salesdata.php?fromyear=2006&toyear=2009&regionid=1';

			$curlHandle = curl_init();
			curl_setopt($curlHandle, CURLOPT_URL, $url);
			curl_setopt($curlHandle, CURL_HTTP_VERSION_1_1, true);
			
			//$headerValue = "WRAPv0.8" . " " . urldecode($token); 
			$headerValue = $token; 
			curl_setopt($curlHandle, CURLOPT_HTTPHEADER, Array("X-Authorization: " . $headerValue));  

			curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER,  true);
			curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION,  true);
			curl_setopt($curlHandle, CURLOPT_HTTPGET, true);
			$httpResponse = curl_exec($curlHandle);	
			
			$httpResponse = trim($httpResponse);
						
			$obj = new AtomParser($httpResponse);
			$response = $obj->parseString();
			
			foreach($response as $key=>$value){
				$resSalesData[$response[$key]['Quantity']] = $response[$key]['Year'];
				
			}			  			
				
			$dB = new Database_Conn();

			$dB->prepareSql("select sum(so.OrderQty) as Quantity,date_format(so.OrderDate,'%Y') as Year from salesorder so inner join salesperson sp  on so.salespersonid = sp.salespersonid  and sp.regionid ='1'  group by date_format(so.OrderDate,'%Y')  ");
			$salesOrderArray = $dB->getResults();

			foreach($salesOrderArray as $key=>$value){
				$SalesData[$salesOrderArray[$key]['Quantity']] = $salesOrderArray[$key]['Year'];
			}	
			// Verification  part 
			for($i=1; $i<=count($SalesData);$i++){				
				$this->assertEquals($SalesData[$i]['Quantity'],$resSalesData[$i]["Quantity"]);    
				$this->assertEquals($SalesData[$i]['Year'],$resSalesData[$i]["Year"] );				
			}
				
							
		}
		catch(Exception $exception)
        {	
			 $e->getMessage();
			 throw($e);
        }
		
	}	
	

}
  
 $suite = new PHPUnit_TestSuite();

 $suite->addTest(new SalesDashboardTestCases('testGetRegions')); 
 $suite->addTest(new SalesDashboardTestCases('testGetProducts')); 
 $suite->addTest(new SalesDashboardTestCases('testSalesOrder')); 
 $suite->addTest(new SalesDashboardTestCases('testCreateOrder'));  
 $suite->addTest(new SalesDashboardTestCases('testUpdateOrder'));
 $suite->addTest(new SalesDashboardTestCases('testSalesData'));

 $result = PHPUnit::run($suite);
 print $result->toHTML();
?>
